package com.ima;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.text.InputFilter;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;
import com.dev.ColorTextButton;
import com.dev.CrossZebraDrawable;
import com.dev.GUI;
import com.dev.IconView;
import com.dev.IconViewClose;
import com.dev.MainActivity;
import com.dev.ShowSoftInput;
import com.dev.UnderlineSingleLineEditor;
import com.log;

class QueryPalette extends LinearLayout implements OnClickListener,OnEditorActionListener {
	WindowManager.LayoutParams wlp=new WindowManager.LayoutParams();
	LinearLayout titlebar;
	LinearLayout preset;
	LinearLayout preview;
	LinearLayout editcolor,tw1,tw2,tw3;
	LinearLayout tbs;
	UnderlineSingleLineEditor editor;
	View colored;
	ColorTab ctNow;
	ColorTextButton tbDelete;
	ColorTextButton tbAdd;
	HorizontalScrollView preset_hsv;
	IconView close;
	TextView title;
	TextView preview_title;
	TextView editcolor_title;
	ShowSoftInput ssi;
	int intend;
	int color;
	TextView apply;
	TextView hint1,hint2,hint3;
	MainActivity ma;
	SQLiteDatabase data;
	QueryPalette(MainActivity ma){
		super(ma);
		this.ma=ma;
		setOrientation(VERTICAL);
		setBackground(new GUI.BorderDrawable());
		try{
		msh=new MySQLiteOpenHelper();
		data=msh.getWritableDatabase();
		}catch(Exception e){log.alert(e.toString());}
		close=new IconViewClose(ma);
		close.setOnClickListener(this);
		title=new TextView(ma);
		title.setGravity(Gravity.CENTER_VERTICAL);
		int padding=10;
		ssi=new ShowSoftInput(ma);
		ssi.setOnClickListener(this);
		title.setPadding(padding,0,0,0);
		title.setTextSize(TypedValue.COMPLEX_UNIT_DIP,13);
		title.setGravity(Gravity.CENTER_VERTICAL);
		titlebar=new LinearLayout(ma);
		titlebar.setOrientation(HORIZONTAL);
		titlebar.setBackground(new GUI.BorderDrawable());
		titlebar.addView(title,new LayoutParams(0,-1,1f));
		titlebar.addView(ssi);
		titlebar.addView(close);
		preset=new LinearLayout(ma);
		preset.setOrientation(HORIZONTAL);
		try{
			Cursor cur=data.query("colors",null,null,null,null,null,"`index`");
			int col=cur.getColumnIndex("color");
			for(int index=0;cur.moveToNext()&&index<40;index++){
				if(index<40){
					ColorTab ct=new ColorTab(cur.getInt(col));
					ct.setOnClickListener(this);
					preset.addView(ct);
				}else{
					log.alert("异常，数据库条目数量大于40");
				}

			}
		}catch(Exception e){
			log.alert(e.toString());
		}
		preset_hsv=new HorizontalScrollView(ma);
		preset_hsv.setHorizontalScrollBarEnabled(false);
		preset_hsv.addView(preset);
		preset_hsv.setFillViewport(true);
		preset_hsv.setPadding(9,9,9,9);
		preview_title=new TextView(ma);
		preview_title.setGravity(Gravity.CENTER_VERTICAL);
		preview_title.setPadding(padding,0,0,0);
		preview_title.setTextSize(TypedValue.COMPLEX_UNIT_DIP,13);
		preview_title.setText("预览：");
		tbDelete=new ColorTextButton(ma);
		tbDelete.setText(" 删除预设 ");
		tbDelete.setOnClickListener(this);
		tbAdd=new ColorTextButton(ma);
		tbAdd.setText(" 添加预设 ");
		tbAdd.setOnClickListener(this);
		tbs=new LinearLayout(ma);
		tbs.setOrientation(0);
		tbs.addView(tbDelete);
		tbs.addView(tbAdd);
		colored=new View(ma){
			@Override 
			public void onDraw(Canvas canvas){
				super.onDraw(canvas);
				canvas.drawColor(color);
			}
		};
		colored.setBackground(new CrossZebraDrawable(9));
		apply=new ColorTextButton(ma);
		apply.setText(" 应用 ");
		apply.setOnClickListener(this);
		preview=new LinearLayout(ma);
		preview.setOrientation(HORIZONTAL);
		preview.addView(preview_title,-2,-1);
		preview.addView(colored,new LayoutParams(0,-1,1f));
		preview.addView(apply,-2,-1);
		editor=new UnderlineSingleLineEditor(ma);
		editor.setPadding(padding,0,padding,0);
		editor.setFilters(new InputFilter[]{
							  new InputFilter.LengthFilter(8)
						  });
		editor.setImeOptions(EditorInfo.IME_ACTION_DONE);
		editor.setOnEditorActionListener(this);
		editcolor=new LinearLayout(ma);
		editcolor_title=new TextView(ma);
		editcolor_title.setTextSize(TypedValue.COMPLEX_UNIT_DIP,13);
		editcolor_title.setGravity(Gravity.CENTER_VERTICAL);
		editcolor_title.setText("颜色值：#");
		editcolor_title.setPadding(padding,0,0,0);
		editcolor.setOrientation(HORIZONTAL);
		editcolor.addView(editcolor_title,-2,-1);
		editcolor.addView(editor,new LayoutParams(0,-1,1f));
		tw1=new LinearLayout(ma);
		tw2=new LinearLayout(ma);
		tw3=new LinearLayout(ma);
		tw1.setOrientation(HORIZONTAL);
		tw2.setOrientation(HORIZONTAL);
		tw3.setOrientation(HORIZONTAL);
		hint1=new TextView(ma);
		hint2=new TextView(ma);
		hint3=new TextView(ma);
		hint1.setPadding(padding,0,0,0);
		hint2.setPadding(padding,0,0,0);
		hint3.setPadding(padding,0,0,0);
		hint1.setGravity(Gravity.CENTER_VERTICAL);
		hint2.setGravity(Gravity.CENTER_VERTICAL);
		hint3.setGravity(Gravity.CENTER_VERTICAL);
		int textSize=(int)(13*ma.dp);
		hint1.getPaint().setTextSize(textSize);
		hint2.getPaint().setTextSize(textSize);
		hint3.getPaint().setTextSize(textSize);
		hint1.setText("R");
		hint2.setText("G");
		hint3.setText("B");
		LayoutParams hintlp=new LayoutParams((int)(20*ma.dp),-1);

		addView(titlebar,-1,ma.dialogTitleBarHeight);
		addView(preset_hsv,-1,(int)(40*ma.dp));
		addView(tbs,-1,ma.dialogTitleBarHeight);
		addView(preview,-1,ma.dialogTitleBarHeight);
		addView(editcolor,-1,ma.dialogTitleBarHeight);

	}
	void savePreset(){
		try{
		data.execSQL("DELETE FROM colors");
		for(int index=0,count=preset.getChildCount();index<count;index++){
			View child=preset.getChildAt(index);
			ColorTab ct=(ColorTab)child;
			data.execSQL(String.format("INSERT INTO colors VALUES(%d,%d)",index,ct.color));
		}
		}catch(Exception e){log.alert(e.toString());}
	}
	ImageManipulationPage imp;
	void show(ImageManipulationPage imp,int intend){
		this.intend=intend;
		this.imp=imp;
		wlp.width=ma.wp*4/5;
		wlp.height=-2;
		if(intend==0){
			title.setText("选择前景色");
			color=imp.foregroundColor;
		}else if(intend==1){
			title.setText("选择背景色");
			color=imp.backgroundColor;
		}
		editor.setText(String.format("%08x",color));
		ma.wm.addView(this,wlp);
	}

	@Override
	public boolean onEditorAction(TextView textView, int p, KeyEvent keyEvent) {
		if(textView==editor){
			String userinput=textView.getText().toString();
			if(userinput.isEmpty()){
				Toast.makeText(ma,"无输入",0).show();
				return true;
			}else{
				try{
					long l=Long.parseLong(userinput,16);
					long max=(0l|-1)>>>32;
					if(l>=0&&l<=max){
						color=(int)l;
						colored.invalidate();
					}else{
						Toast.makeText(ma,"只能为#00000000~#ffffffff",0).show();
					}
				}catch(Exception e){
					Toast.makeText(ma,"无法识别输入内容",0).show();
				}
				return true;
			}
		}
		return false;
	}
	@Override
	public void onClick(View view) {
		if(view==close){
			ma.wm.removeView(this);
		}else if(view==apply){
			if(intend==0){
				imp.foregroundColor=color;
				ma.wm.removeView(this);
				imp.colorReveal.invalidate();
			}else if(intend==1){
				imp.backgroundColor=color;
				ma.wm.removeView(this);
				imp.colorReveal.invalidate();
			}
		}else if(view==ssi){
			if(editor.requestFocus()){
				ma.imm.showSoftInput(editor,0);
				editor.selectAll();
			}
		}else if(view==tbDelete){
			if(ctNow==null){
				Toast toast=Toast.makeText(ma,"先选中一个预设",0);
				toast.setGravity(Gravity.CENTER,0,0);
				toast.show();
			}else{
				preset.removeView(ctNow);
				ctNow=null;
				savePreset();
			}
		}else if(view==tbAdd){
			if(ctNow==null){
				for(int index=0,count=preset.getChildCount();;index++){
					if(index<count){
						ColorTab ct=(ColorTab)preset.getChildAt(index);
						if(ct.color==color){
							Toast toast=Toast.makeText(ma,"已存在相同颜色",0);
							toast.setGravity(Gravity.CENTER,0,0);
							toast.show();
							break;
						}
					}else{
						ColorTab ct=new ColorTab(color);
						ct.setOnClickListener(this);
						preset.addView(ct);
						savePreset();
						break;
					}
				}
			}else{
				for(int index=0,count=preset.getChildCount();;index++){
					if(index<count){
						ColorTab ct=(ColorTab)preset.getChildAt(index);
						if(ct.color==color){
							Toast.makeText(ma,"无需此操作",0).show();
							break;
						}
					}else{
						ctNow.color=color;
						savePreset();
						break;
					}
				}
			}
		}else if(view instanceof ColorTab){
			ColorTab colortab=(ColorTab)view;
			color=colortab.color;
			editor.setText(String.format("%08x",color));
			colored.invalidate();
			if(ctNow==null){
				ctNow=colortab;
				ctNow.setSelected(true);
			}else if(ctNow==colortab){
				ctNow.setSelected(false);
				ctNow=null;
			}else{
				ctNow.setSelected(false);
				ctNow=colortab;
				ctNow.setSelected(true);
			}
		}
	}
	class ColorTab extends View{
		int color;
		ColorTab(int color){
			super(ma);
			this.color=color;
		}

		@Override
		protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
			int h=MeasureSpec.getSize(heightMeasureSpec);
			setMeasuredDimension(h,h);
		}

		@Override
		protected void onDraw(Canvas canvas) {
			super.onDraw(canvas);
			final int vw=getWidth();
			final int vh=getHeight();
			int padding=vw/15;
			Paint p=new Paint();
			final int borderWidth=(int)(3*ma.dp);
			final int out=borderWidth/2;
			if(isSelected()){
				p.setColor(0xffffffff);
				canvas.drawRect(padding,padding,padding+out,vh-padding,p);
				canvas.drawRect(padding,padding,vw-padding,padding+out,p);
				canvas.drawRect(vw-padding-out,padding,vw-padding,vh-padding,p);
				canvas.drawRect(padding,vh-padding-out,vw-padding,vh-padding,p);
				p.setColor(0xff000000);
				canvas.drawRect(padding+out,padding+out,padding+borderWidth,vh-padding-out,p);
				canvas.drawRect(padding+out,padding+out,vw-padding-out,padding+borderWidth,p);
				canvas.drawRect(vw-padding-borderWidth,padding+out,vw-padding-out,vh-padding-out,p);
				canvas.drawRect(padding+out,vh-padding-borderWidth,vw-padding-out,vh-padding-out,p);
			}else{
				p.setColor(0xff000000);
				canvas.drawRect(padding,padding,padding+out,vh-padding,p);
				canvas.drawRect(padding,padding,vw-padding,padding+out,p);
				canvas.drawRect(vw-padding-out,padding,vw-padding,vh-padding,p);
				canvas.drawRect(padding,vh-padding-out,vw-padding,vh-padding,p);
				p.setColor(0xffffffff);
				canvas.drawRect(padding+out,padding+out,padding+borderWidth,vh-padding-out,p);
				canvas.drawRect(padding+out,padding+out,vw-padding-out,padding+borderWidth,p);
				canvas.drawRect(vw-padding-borderWidth,padding+out,vw-padding-out,vh-padding-out,p);
				canvas.drawRect(padding+out,vh-padding-borderWidth,vw-padding-out,vh-padding-out,p);
			}

			int zebra=(int)(4*ma.dp);
			int start=zebra/2;
			canvas.clipRect(padding+borderWidth,padding+borderWidth,vw-padding-borderWidth,vh-padding-borderWidth);
			p.setColor(0xff000000);
			for(int x=padding+borderWidth-start;x<vw-padding-borderWidth;x+=zebra){
				for(int y=padding+borderWidth-start;y<vh-padding-borderWidth;y+=zebra*2){
					canvas.drawRect(x,y,x+zebra,y+zebra,p);
				}
				x+=zebra;
				for(int y=padding+borderWidth-start-zebra;y<vh-padding-borderWidth;y+=zebra*2){
					canvas.drawRect(x,y,x+zebra,y+zebra,p);
				}
			}
			canvas.drawColor(color);
		}
	}
	class Tweaker extends View{
		Tweaker(){
			super(ma);
		}
	}
	MySQLiteOpenHelper msh;
	class MySQLiteOpenHelper extends SQLiteOpenHelper {
		MySQLiteOpenHelper(){
			super(ma,MySQLiteOpenHelper.class.getCanonicalName(),null,1);
		}
		@Override
		public void onCreate(SQLiteDatabase sQLiteDatabase) {
			sQLiteDatabase.execSQL("CREATE TABLE colors(`index` INTEGER IDENTITY(0,1) PRIMARY KEY,`color` INTEGER)");
			sQLiteDatabase.execSQL(String.format("INSERT INTO colors VALUES(%d,%d)",0,0xff00ff00));
			sQLiteDatabase.execSQL(String.format("INSERT INTO colors VALUES(%d,%d)",1,0xffff0000));
			sQLiteDatabase.execSQL(String.format("INSERT INTO colors VALUES(%d,%d)",2,0xff0000ff));
			sQLiteDatabase.execSQL(String.format("INSERT INTO colors VALUES(%d,%d)",3,0xffffff00));
			sQLiteDatabase.execSQL(String.format("INSERT INTO colors VALUES(%d,%d)",4,0xffff00ff));
			sQLiteDatabase.execSQL(String.format("INSERT INTO colors VALUES(%d,%d)",5,0xff00ffff));
			sQLiteDatabase.execSQL(String.format("INSERT INTO colors VALUES(%d,%d)",6,0xff000000));
			sQLiteDatabase.execSQL(String.format("INSERT INTO colors VALUES(%d,%d)",7,0xffffffff));
			sQLiteDatabase.execSQL(String.format("INSERT INTO colors VALUES(%d,%d)",8,0x00ffffff));
			sQLiteDatabase.execSQL(String.format("INSERT INTO colors VALUES(%d,%d)",9,0xff00bbff));
		}

		@Override
		public void onUpgrade(SQLiteDatabase sQLiteDatabase, int p, int p1) {
		}
	}
}
